<script
	lang="ts"
	setup
>
import { systemMessagePost, userListGet } from '@/api'
import EmptyModal from '@/components/EmptyModal.vue'
import type { ISystemMessagePost } from '@/typed/request'
import { debounce } from '@/utils'
import type { SelectRenderLabel, SelectRenderTag } from 'naive-ui'
import { type FormInst, type FormRules, NAvatar, NTag, NText, type SelectOption } from 'naive-ui'
import { h, ref, watch } from 'vue'

interface IProps {
	show: boolean;
	width?: number | string;
}

const formRef = ref<FormInst | null>(null)
const emit = defineEmits(['update:show', 'update:list', 'cancel'])
const props = withDefaults(defineProps<IProps>(), {
	width: 500
})
const initForm: ISystemMessagePost = {
	title: '',
	content: '',
	groupType: 'single',
	toUserNos: []
};

const loading = ref(false)
const searchLoading = ref(false)
const modalForm = ref<ISystemMessagePost>({ ...initForm })
const userList = ref<SelectOption[]>([])
const groupTypeList = ref<SelectOption[]>([
	{
		label: '单用户',
		value: 'single'
	},
	{
		label: '全部用户',
		value: 'group'
	}
])
const rules: FormRules = {
	title: [{
		required: true,
		message: '请输入标题',
		trigger: ['blur', 'input']
	}],
	content: [{
		required: true,
		message: '请输入消息内容',
		trigger: ['blur', 'input']
	}],
}

watch(() => modalForm.value.groupType, () => {
	if (modalForm.value.groupType === 'group') {
		modalForm.value.toUserNos = []
	}
})

watch(() => props.show, async () => {
	if (props.show) {
		await getUserList()
	}
})

async function getUserList(keyword?: string) {
	searchLoading.value = true
	const { data } = await userListGet({
		pageNum: 1,
		pageSize: 20,
		keyword
	})
	searchLoading.value = false
	userList.value = data.map((item) => ({
		label: item.name,
		value: item.userNo,
		...item,
	}))
}

const debouncedOnSearch = debounce(async function (query: string) {
	if (!query.length) {
		return;
	}
	await getUserList(query);
	console.log(query)
}, 300);

async function onConfirm() {
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			loading.value = true
			const { code } = await systemMessagePost({
				...modalForm.value
			})
			loading.value = false
			if (code === 200) {
				window.$message.success('保存成功')
				modalForm.value = { ...initForm }

				emit('update:list')
			}
		}
	})
}

function onUpdateShow(show: boolean) {
	emit('update:show', show)
}

const renderMultipleSelectTag: SelectRenderTag = (params: any) => {
	const {
		option,
		handleClose
	} = params;
	return h(
		NTag,
		{
			style: {
				padding: '0 6px 0 4px'
			},
			round: true,
			closable: true,
			onClose: (e) => {
				e.stopPropagation()
				handleClose()
			}
		},
		{
			default: () =>
				h(
					'div',
					{
						style: {
							display: 'flex',
							alignItems: 'center'
						}
					},
					[
						h(NAvatar, {
							src: option.avatarUrl,
							round: true,
							size: 22,
							style: {
								marginRight: '4px',
								flexShrink: 0,
							}
						}),
						option.label as string
					]
				)
		}
	)
}
const renderSingleSelectTag: SelectRenderTag = ({ option }: any) => {
	return h(
		'div',
		{
			style: {
				display: 'flex',
				alignItems: 'center'
			}
		},
		[
			h(NAvatar, {
				src: option.avatarUrl,
				round: true,
				size: 24,
				style: {
					marginRight: '12px',
					flexShrink: 0,
				}
			}),
			option.label as string
		]
	)
}
const renderLabel: SelectRenderLabel = (option: any) => {
	return h(
		'div',
		{
			style: {
				display: 'flex',
				alignItems: 'center'
			}
		},
		[
			h(NAvatar, {
				src: option.avatarUrl,
				round: true,
				size: 'small',
				style: {
					flexShrink: 0,
				}
			}),
			h(
				'div',
				{
					style: {
						marginLeft: '12px',
						padding: '4px 0'
					}
				},
				[
					h('div', null, [option.label as string]),
					h(
						NText,
						{ depth: 3, tag: 'div' },
						{
							default: () => 'description'
						}
					)
				]
			)
		]
	)
}
</script>

<template>
	<EmptyModal
		:show="show"
		@update:show="onUpdateShow"
		:loading="loading"
		:width="600"
		title="添加系统消息"
		@confirm="onConfirm"
		@close="emit('cancel')"
		@cancel="emit('cancel')"
	>
		<n-form
			ref="formRef"
			:model="modalForm"
			label-placement="left"
			label-width="110"
			:rules="rules"
		>
			<n-form-item
				label="消息标题"
				path="title"
			>
				<n-input
					placeholder="请输入标题"
					v-model:value="modalForm.title"
				/>
			</n-form-item>
			<n-form-item
				label="消息内容"
				path="content"
			>
				<n-input
					type="textarea"
					placeholder="请输入消息内容"
					v-model:value="modalForm.content"
				/>
			</n-form-item>
			<n-form-item
				label="群发类型"
				path="toUserNos"
			>
				<n-select
					placeholder="请选择群发类型"
					:options="groupTypeList"
					v-model:value="modalForm.groupType"
				/>
			</n-form-item>
			<n-form-item
				label="接收用户"
				path="toUserNos"
			>
				<n-select
					:disabled="modalForm.groupType === 'group'"
					placeholder="请选择用户"
					multiple
					filterable
					clearable
					remote
					:clear-filter-after-select="false"
					:options="userList"
					v-model:value="modalForm.toUserNos"
					:loading="searchLoading"
					@search="debouncedOnSearch"

					:render-label="renderLabel"
					:render-tag="renderMultipleSelectTag"
				/>
			</n-form-item>
		</n-form>
	</EmptyModal>
</template>

<style
	lang="less"
	scoped
>

</style>
